package com.facedemo.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.facedemo.BuildConfig;
import com.facedemo.R;
import com.facedemo.face.FaceInfoManger;
import com.facedemo.face.FaceLicenseManger;
import com.facedemo.face.callback.LicenseCallback;
import com.facedemo.utils.PermissionUtils;
import com.facedemo.utils.SharePreferencesUtils;

import java.util.List;

//授权初始化界面
public class InitActivity extends AppCompatActivity {
    private LinearLayout ll_toAuth;
    private TextView textView;
    private EditText editText,et_license_info;
    private Button bt_init;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_init);
        initView();
        initPermission();

        new Thread(new Runnable() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0x85);
                if(FaceLicenseManger.toInitLicense()) {
                    mHandler.sendEmptyMessage(0x82);
                    //加载人脸库
                    FaceInfoManger.getInstance().loadFaceFromDb();

                    mHandler.sendEmptyMessage(0x83);

                } else {
                    mHandler.sendEmptyMessage(0x84);
                }
            }
        }).start();
    }

    private void initView() {
        ll_toAuth = findViewById(R.id.ll_toAuth);
        textView = findViewById(R.id.tv_show_res);
        editText = findViewById(R.id.et_com_info);
        et_license_info = findViewById(R.id.et_license_info);
        if(BuildConfig.FLAVOR.equals("authLocal")) {
            et_license_info.setVisibility(View.VISIBLE);
        } else {
            et_license_info.setVisibility(View.GONE);
        }
        bt_init = findViewById(R.id.bt_init_main);
    }

    View.OnClickListener clickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String com = editText.getText().toString().trim();
            String code = "";
            if (com.length() == 0) {
                Toast.makeText(InitActivity.this, "公司授权关键字不能为空", Toast.LENGTH_SHORT).show();
                return;
            }

            if(BuildConfig.FLAVOR.equals("authLocal")) { //离线授权
                code = et_license_info.getText().toString().trim();
                if (code.length() == 0) {
                    Toast.makeText(InitActivity.this, "公司授权码不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
            }
            textView.setText("请稍后...");
            bt_init.setEnabled(false);
            editText.setEnabled(false);
            et_license_info.setEnabled(false);

            if(BuildConfig.FLAVOR.equals("authLocal")) { //离线授权
                SharePreferencesUtils.putString(InitActivity.this,FaceLicenseManger.LICENSE_KEY,com+"\0");
                SharePreferencesUtils.putString(InitActivity.this,FaceLicenseManger.LICENSE_CODE,code+"\0");

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        if(FaceLicenseManger.toInitLicense()) {
                            mHandler.sendEmptyMessage(0x82);
                            //加载人脸库
                            FaceInfoManger.getInstance().loadFaceFromDb();

                            mHandler.sendEmptyMessage(0x83);

                        } else {
                            Message msg = new Message();
                            msg.what = 0x81;
                            msg.obj = "初始化失败";
                            mHandler.sendMessage(msg);
                        }
                    }
                }).start();

            } else { //在线授权
                FaceLicenseManger.toGetLicenseOnline(com, new LicenseCallback() {
                    @Override
                    public void success(String key, String licenseCode) {
                        mHandler.sendEmptyMessage(0x82);
                        //加载人脸库
                        FaceInfoManger.getInstance().loadFaceFromDb();

                        mHandler.sendEmptyMessage(0x83);
                    }

                    @Override
                    public void failed(String errorMsg) {
                        Message msg = new Message();
                        msg.what = 0x81;
                        msg.obj = errorMsg;
                        mHandler.sendMessage(msg);
                    }
                });
            }
        }
    };

    @SuppressLint("HandlerLeak")
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0x85:
                    ll_toAuth.setVisibility(View.GONE);
                    textView.setText("正在初始化...");
                    break;
                case 0x82:
                    textView.setText("加载人脸...");
                    break;
                case 0x83:
                    Intent intent = new Intent(InitActivity.this,MainActivity.class);
                    startActivity(intent);
                    finish();
                    break;
                case 0x84:
                    ll_toAuth.setVisibility(View.VISIBLE);
                    textView.setText("");
                    bt_init.setOnClickListener(clickListener);
                    break;
                case 0x81:
                    editText.setEnabled(true);
                    et_license_info.setEnabled(true);
                    bt_init.setEnabled(true);
                    textView.setText((String)msg.obj);
                    break;
            }
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mHandler!=null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

    //-------------------------系统授权----------------------
    private final int PERMISSIONS_REQUES_CODE = 0X88;
    private final String[] permissions = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.ACCESS_WIFI_STATE};
    private void initPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissionList = PermissionUtils.checkMorePermissions(InitActivity.this, permissions);
            if (permissionList.size() > 0) { // 未授权的权限
                //申请获取权限
                PermissionUtils.requestMorePermissions(InitActivity.this, permissionList, PERMISSIONS_REQUES_CODE);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case PERMISSIONS_REQUES_CODE:
                PermissionUtils.onRequestMorePermissionsResult(InitActivity.this, permissions, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                        showToAppSettingDialog();
                    }
                });
                break;
            default:
                break;
        }
    }

    //显示前往应用设置Dialog
    private void showToAppSettingDialog() {
        new AlertDialog.Builder(this)
                .setTitle("需要权限")
                .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        PermissionUtils.toAppSetting(InitActivity.this);
                    }
                })
                .setNegativeButton("取消", null)
                .show();
    }
}
